#!/usr/bin/python2.4

import datetime
import os
import random
import simplejson
import time
import urllib
import urllib2

from mod_python import apache

class UrlFactory:
    BASE_URL = 'http://picasaweb.google.com/data/feed/api/user'

    def MakeAlbumListUrl(user):
        return '%s/%s?kind=album&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user)
        )
    MakeAlbumListUrl = staticmethod(MakeAlbumListUrl)

    def MakeAlbumUrl(user, album):
        return '%s/%s/album/%s?kind=photo&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user),
            urllib.quote(album.replace(' ', ''))
        )
    MakeAlbumUrl = staticmethod(MakeAlbumUrl)

    def MakeAlbumIdUrl(user, albumid):
        return '%s/%s/albumid/%s?kind=photo&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user),
            urllib.quote(albumid)
        )
    MakeAlbumIdUrl = staticmethod(MakeAlbumIdUrl)

    def MakePhotoIdUrl(user, photoid):
        return '%s/%s/photoid/%s?kind=photo&alt=json' % (
            UrlFactory.BASE_URL,
            urllib.quote(user),
            urllib.quote(photoid)
        )
    MakePhotoIdUrl = staticmethod(MakePhotoIdUrl)

# template args:
#  dtstart.{year, month, day}
#  dtend.{year, month, day}
#  description
#  title
#  title
#  icon
#  type
#  url
#  width
#  height
TEMPLATE = """BEGIN:VCALENDAR
PRODID:-//Pedro Colijn//PicasaWeb Content Calendar 0.1//EN
VERSION:2.0
X-WR-CALNAME:PicasaWeb: %s
X-WR-CALDESC:PicasaWeb content calendar for %s
BEGIN:VEVENT
DTSTART;VALUE=DATE:%04d%02d%02d
DTEND;VALUE=DATE:%04d%02d%02d
SEQUENCE:1
UID:%s
DESCRIPTION:%s
SUMMARY:%s
X-GOOGLE-CALENDAR-CONTENT-TITLE:%s
X-GOOGLE-CALENDAR-CONTENT-ICON:%s
X-GOOGLE-CALENDAR-CONTENT-TYPE:%s
X-GOOGLE-CALENDAR-CONTENT-URL:%s
X-GOOGLE-CALENDAR-CONTENT-WIDTH:%d
X-GOOGLE-CALENDAR-CONTENT-HEIGHT:%d
END:VEVENT
END:VCALENDAR"""

ICON = 'http://colijn.ca/~caffeine/lhcal/lhcalicon.gif'


def __icalescape__(str):
    str = str.replace('\\', '\\\\')
    str = str.replace('\n', '\\n')
    str = str.replace('\t', '\\t')
    str = str.replace(',', '\\,')
    str = str.replace(';', '\\;')
    return str


def __generate__(username, photoentry, startdt):
    username = __icalescape__(username)
    enddt = startdt + datetime.timedelta(1)
    summary = __icalescape__(photoentry['summary']['$t'])
    if summary in (None, ''):
        summary = 'PicasaWeb photo of the day'

    type = __icalescape__(photoentry['content']['type'])

    thumbnailindex = len(photoentry['media$group']['media$thumbnail']) - 1
    thumbnail = photoentry['media$group']['media$thumbnail'][thumbnailindex]

    url = __icalescape__(thumbnail['url'])
    icon = __icalescape__(ICON)
    width = int(thumbnail['width'])
    height = int(thumbnail['height'])

    uid = __icalescape__(
        '%s#%s#%s' % (
            photoentry['gphoto$id']['$t'],
            photoentry['gphoto$timestamp']['$t'],
            'lhcal_01'))

    return TEMPLATE % (
        username, username,
        startdt.year, startdt.month, startdt.day,
        enddt.year, enddt.month, enddt.day,
        uid,
        summary, summary, summary,
        icon,
        type,
        url,
        width,
        height
    )


def __get__(url):
    resp = None
    try:
        resp = urllib2.urlopen(url)
        return simplejson.load(resp)
    except urllib2.URLError, e:
        return None


def ical(req, user, tzoffset, excludes):
    albumlist_url = UrlFactory.MakeAlbumListUrl(user)
    albumlist = __get__(albumlist_url)
    if albumlist is None:
        req.status = apache.HTTP_NOT_FOUND
        req.content_type = 'text/plain; charset=UTF8'
        req.write("Could not download '%s'" % albumlist_url)
        return

    # sick and dirty hack
    os.environ['TZ'] = 'GMT'

    timestamp = time.time() - float(tzoffset) * 60.0
    date = datetime.date.fromtimestamp(timestamp)
    seed = user.__hash__() * 0x1001 + date.month * 0x101 + date.day * 0x11
    random.seed(seed)

    excluded = {}
    for exclude in excludes.split(','):
        excluded[exclude] = True

    albumentries = []
    for album in albumlist['feed']['entry']:
        if album['gphoto$id']['$t'] in excluded:
            continue

        albumentries.append(album)

    albumentry = albumentries[random.randint(0, len(albumentries) - 1)]
    albumid = albumentry['gphoto$id']['$t']
    albumtimestamp = albumentry['gphoto$timestamp']['$t']

    album_url = UrlFactory.MakeAlbumIdUrl(user, albumid)
    album = __get__(album_url)
    if album is None:
        req.status = apache.HTTP_NOT_FOUND
        req.content_type = 'text/plain; charset=UTF8'
        req.write("Could not download '%s'" % album_url)
        return

    photoentries = album['feed']['entry'];
    photoentry = photoentries[random.randint(0, len(photoentries) - 1)]

    req.content_type = 'text/calendar; charset=UTF-8'
    req.write(__generate__(user, photoentry, date))
